﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Dbz.HomeworkHub.Frontend.Attributes;

namespace Dbz.HomeworkHub.Frontend
{
    // Hinweis: Anweisungen zum Aktivieren des klassischen Modus von IIS6 oder IIS7 
    // finden Sie unter "http://go.microsoft.com/?LinkId=9394801".

    public class MvcApplication : System.Web.HttpApplication
    {
        public MvcApplication()
            : base()
        {
            if (Controllers.BaseController.BusinessObjectCache == null)
                Controllers.BaseController.BusinessObjectCache = new Dictionary<HttpRequest, Core.BusinessObjects>();
        }

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new UserContextAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Routenname
                "{controller}/{action}/{id}", // URL mit Parametern
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameterstandardwerte
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }


        protected void Application_BeginRequest()
        {
            lock (Controllers.BaseController.BusinessObjectCache)
            {
                Controllers.BaseController.BusinessObjectCache.Add(HttpContext.Current.Request, new Core.BusinessObjects());
            }
        }

        protected void Application_EndRequest()
        {
            lock (Controllers.BaseController.BusinessObjectCache)
            {
                if (Controllers.BaseController.BusinessObjectCache.ContainsKey(HttpContext.Current.Request))
                {
                    Dbz.HomeworkHub.Core.BusinessObjects businessObjects = Controllers.BaseController.BusinessObjectCache[HttpContext.Current.Request];
                    Controllers.BaseController.BusinessObjectCache.Remove(HttpContext.Current.Request);
                    businessObjects.Dispose();
                }
            }
        }
 
    }
}